package com.xsomnus.network_programming.netty.udpchat;

import com.xsomnus.network_programming.netty.udpchat.config.UdpProperties;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.charset.StandardCharsets;

/**
 * @author @叶小夏
 * @since 2019/8/9 0009 10:08
 * - 才需学也,学需静也/非淡泊无以明志，非宁静无以致远
 */
public class LocalUDPReceiver {

    private static LocalUDPReceiver instance = null;
    private Thread thread = null;


    public static LocalUDPReceiver getInstance() {
        if (instance == null)
            instance = new LocalUDPReceiver();
        return instance;
    }

    public void startup() {
        this.thread = new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("本地UDP端口侦听中，端口=" + UdpProperties.localUDPPort + "...");

                    //开始侦听
                    LocalUDPReceiver.this.udpListeningImpl();
                } catch (Exception eee) {
                    System.out.println("本地UDP监听停止了(socket被关闭了?)," + eee.getMessage() + eee);
                }
            }
        });
        this.thread.start();
    }

    private void udpListeningImpl() throws Exception {
        while (true) {
            byte[] data = new byte[1024];
            // 接收数据报的包
            DatagramPacket packet = new DatagramPacket(data, data.length);

            DatagramSocket localUDPSocket = LocalUDPSocketProvider.getInstance().getLocalUDPSocket();
            if ((localUDPSocket == null) || (localUDPSocket.isClosed()))
                continue;

            // 阻塞直到收到数据
            localUDPSocket.receive(packet);

            // 解析服务端发过来的数据
            String pFromServer = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8);
            System.out.println("【NOTE】>>>>>> 收到服务端的消息：" + pFromServer);
        }
    }
}
